var formEl;
apiready = function() {
    app.ready();

    formEl = $api.dom('#form-login');
    app.addEvt($api.domAll('#form-login input[name]'), 'input', function() {
        validInput();
    });

    app.addEvt($api.dom('#btn-login'), 'click', function() {
        doLogin();
    });

    window.onkeydown = function(event) {
        if (event.keyCode == 13) {
            if (event.target.name == 'password') {
                doLogin();
                app.stopDefault(event);
            }
        }
    }
};

function validInput() {
    var values = app.getFormValues(formEl);
    var btnLogin = $api.dom('#btn-login');
    if (values.phone.length == 11 && values.password.length > 0) {
        $api.removeCls(btnLogin, 'disabled');
        return true;
    } else {
        $api.addCls(btnLogin, 'disabled');
        return false;
    }
}

function doLogin() {
    if (validInput()) {
        var options = service.get('login');
        var values = app.getFormValues(formEl);
        app.formSubmit(formEl, app.extend({
            data: {
                values: {
                    oauth: 'Sms',
                    //jpush_token: ,
                    version: app.appVersion,
                    type: 'password',
                    phone: values.phone,
                    password: values.password
                }
            },
            onSuccess: function(req, ret) {
                var user = eval(ret.content);
                user.refreshTime = new Date();
                $api.setStorage('user', JSON.stringify(user));
                app.setAccessToken(ret.content.access_token);
                api.toast({
                    msg: '登录成功！',
                    duration: 2000,
                    location: 'bottom'
                });
                api.closeToWin({
                    name: 'root'
                });
            },
            onError: function(ret, err) {
                api.toast({
                    msg: ret.message || '登录失败',
                    duration: 2000,
                    location: 'bottom'
                });
            }
        }, options));
    }
}
